package cn.wu.reggie.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.wu.reggie.common.Page;
import cn.wu.reggie.common.R;
import cn.wu.reggie.entity.Category;
import cn.wu.reggie.entity.Dish;
import cn.wu.reggie.entity.Setmeal;
import cn.wu.reggie.exception.BusinessException;
import cn.wu.reggie.mapper.CategoryMapper;
import cn.wu.reggie.mapper.DishMapper;
import cn.wu.reggie.mapper.SetmealMapper;
import cn.wu.reggie.service.CategoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {


    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;


    @Override
    public R findByPage(Integer pageNum, Integer pageSize) {

        // 1 设置分页参数
        PageHelper.startPage(pageNum,pageSize);
        // 2 查询列表
        List<Category> list = categoryMapper.findAll();
        //3 用pageInfo封装列表
        PageInfo<Category> pageInfo = new PageInfo<>(list);
        // 4 封装返回类型
        Page<Category> page = new Page(pageInfo.getList(), pageInfo.getTotal());


        return R.success(page);
    }

    @Override
    public R save(Category category) {
        // 封装时间
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(category.getCreateTime());
        // 调用mapper完成保存
        categoryMapper.save(category);
        return R.success(null);
    }

    @Override
    public R update(Category category) {
        // 封装时间
        category.setUpdateTime(LocalDateTime.now());
        // 调用mapper完成修改
        categoryMapper.update(category);
        return R.success(null);
    }


    // 不需要加事务的注解 因为只是查询操作不影响 就算是删除也不影响因为抛错误后会回滚
    @Override
    public R delete(Long id) {

        // 通过分类id看此分类下有没有菜品或者套餐
        List<Dish> dishList = dishMapper.findByCategoryId(id);
        if (CollUtil.isNotEmpty(dishList)){
            throw new BusinessException("该分类下有菜品，不能删除");
        }

        List<Setmeal> setmealList = setmealMapper.findByCategoryId(id);
        if (CollUtil.isNotEmpty(setmealList)){
            throw new BusinessException("该分类下有套餐 不能删除");
        }

        // 调用categoryMapper完成删除
        categoryMapper.delete(id);
        return R.success(null);
    }

    @Override
    public R findAllByType(Integer type) {
        List<Category> list = categoryMapper.findAllByType(type);
        return R.success(list);
    }


}
